package com.conan.zone.util.ibatis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.conan.zone.util.ReflectionUtils;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.engine.execution.SqlExecutor;
import com.ibatis.sqlmap.engine.impl.SqlMapClientImpl;
import com.ibatis.sqlmap.engine.impl.SqlMapExecutorDelegate;

/**
 * 用于生成SqlMapClient,但增加设置sqlExecutor属性,以便用于扩展iBATIS使用数据库物理分页
 * 
 * @author 孙坚
 * 
 */
public class SqlMapClientFactoryBean extends
		org.springframework.orm.ibatis.SqlMapClientFactoryBean {

	private static Logger logger = LoggerFactory
			.getLogger(SqlMapClientFactoryBean.class);

	private SqlExecutor sqlExecutor;

	public SqlExecutor getSqlExecutor() {
		return sqlExecutor;
	}

	public void setSqlExecutor(SqlExecutor sqlExecutor) {
		this.sqlExecutor = sqlExecutor;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		super.afterPropertiesSet();
		SqlMapClient c = (SqlMapClient) getObject();
		if (sqlExecutor != null && c instanceof SqlMapClientImpl) {
			SqlMapClientImpl client = (SqlMapClientImpl) c;
			SqlMapExecutorDelegate delegate = client.getDelegate();
			try {

				ReflectionUtils.setFieldValue(delegate, "sqlExecutor",
						sqlExecutor);
				logger
						.info("[iBATIS] success set ibatis SqlMapClient.sqlExecutor = "
								+ sqlExecutor.getClass().getName());
			} catch (Exception e) {
				logger
						.error("[iBATIS] error,cannot set ibatis SqlMapClient.sqlExecutor = "
								+ sqlExecutor.getClass().getName()
								+ " cause:"
								+ e);
			}
		}
	}
}
